<template>
  <div class="profile-container">
    <!-- 个人信息卡片 -->
    <div class="profile-header">
      <div class="user-info" @click="openDrawer">
        <div class="avatar-wrapper">
          <el-avatar :size="80" :src="user.avatarUrl"></el-avatar>
          <div class="edit-avatar">
            <i class="el-icon-camera"></i>
          </div>
        </div>
        <div class="user-details">
          <div class="user-main-info">
            <h2 class="username">{{ user.username }}</h2>
            <span class="user-age">{{ formatAge(user.age) }}</span>
            <span class="user-gender">{{ user.sex ? '男' : '女' }}</span>
          </div>
          <p class="user-email">{{ user.emali }}</p>
          <p class="user-signature">{{ user.bio || '这个人很懒，什么都没写~' }}</p>
          <el-button type="text" class="edit-btn" @click.stop="editProfile">
            <i class="el-icon-edit"></i> 编辑资料
          </el-button>
        </div>
      </div>
    </div>

    <!-- 用户数据概览 -->
    <div class="user-stats">
      <div class="stat-item">
        <div class="stat-value">{{ shoppingCartItems.length || 0 }}</div>
        <div class="stat-label">购物车</div>
      </div>
      <div class="stat-item">
        <div class="stat-value">{{ favoriteItems.length || 0 }}</div>
        <div class="stat-label">收藏商品</div>
      </div>
      <div class="stat-item">
        <div class="stat-value">{{ collectedPosts.length || 0 }}</div>
        <div class="stat-label">收藏帖子</div>
      </div>
      <div class="stat-item">
        <div class="stat-value">{{ forms.length || 0 }}</div>
        <div class="stat-label">我的帖子</div>
      </div>
    </div>

    <!-- 功能区域 -->
    <div class="features-grid">
      <!-- 我的帖子模块 -->
      <div class="feature-card">
        <div class="card-header">
          <h3><i class="el-icon-edit-outline"></i> 我的帖子</h3>
          <div class="header-actions">
            <el-button type="primary" size="small" @click="createNewPost">
              <i class="el-icon-plus"></i> 发表帖子
            </el-button>
            <el-button type="text">查看全部 <i class="el-icon-arrow-right"></i></el-button>
          </div>
        </div>
        <div class="card-content">
          <template v-if="forms.length">
            <div v-for="form in forms.slice(0, 3)" :key="form.id" class="post-item" @click="clickpost(form.post_id)">
              <span class="post-title">{{ form.title }}</span>
              <span class="post-date">{{ formatDate(form.createdAt) }}</span>
            </div>
          </template>
          <div v-else class="empty-tip">还没有发表过帖子，来分享一下吧~</div>
        </div>
      </div>

      <!-- 购物车模块 -->
      <div class="feature-card" @click="toshoppingcart">
        <div class="card-header">
          <h3><i class="el-icon-shopping-cart-2"></i> 购物车</h3>
          <el-button type="text">查看全部 <i class="el-icon-arrow-right"></i></el-button>
        </div>
        <div class="card-content">
          <template v-if="shoppingCartItems.length">
            <div v-for="item in shoppingCartItems" :key="item.id" class="cart-item">
              <span class="item-name">{{ item.name }}</span>
              <span class="item-price">¥{{ item.price.toFixed(2) }}</span>
            </div>
          </template>
          <div v-else class="empty-tip">购物车还是空的，快去挑选心仪的商品吧~</div>
        </div>
      </div>

      <!-- 商品收藏模块 -->
      <div class="feature-card">
        <div class="card-header">
          <h3><i class="el-icon-star-on"></i> 商品收藏</h3>
          <el-button type="text">查看全部 <i class="el-icon-arrow-right"></i></el-button>
        </div>
        <div class="card-content">
          <template v-if="favoriteItems.length">
            <div v-for="item in favoriteItems.slice(0, 3)" :key="item.id" class="favorite-item">
              <span>{{ item.name }}</span>
            </div>
          </template>
          <template v-else>
            <div class="favorite-item">
              <div class="favorite-item-content">
                <div class="favorite-item-image">
                  <img src="@/assets/images/hualan.jpeg" alt="花兰" />
                </div>
                <div class="favorite-item-info">
                  <div class="favorite-item-name">蓝睡莲花盆栽</div>
                  <div class="favorite-item-price">¥128.00</div>
                </div>
              </div>
              <div class="favorite-item-actions">
                <i class="el-icon-shopping-cart-2" title="加入购物车"></i>
                <i class="el-icon-delete" title="取消收藏"></i>
              </div>
            </div>
            <div class="favorite-item">
              <div class="favorite-item-content">
                <div class="favorite-item-image">
                  <img src="@/assets/images/OIP.jpg" alt="帝王牡丹" />
                </div>
                <div class="favorite-item-info">
                  <div class="favorite-item-name">帝王牡丹精品盆栽</div>
                  <div class="favorite-item-price">¥238.00</div>
                </div>
              </div>
              <div class="favorite-item-actions">
                <i class="el-icon-shopping-cart-2" title="加入购物车"></i>
                <i class="el-icon-delete" title="取消收藏"></i>
              </div>
            </div>
            <div class="favorite-item">
              <div class="favorite-item-content">
                <div class="favorite-item-image">
                  <img src=jung.jpg alt="花卉工具" />
                </div>
                <div class="favorite-item-info">
                  <div class="favorite-item-name">花卉种植工具套装</div>
                  <div class="favorite-item-price">¥89.00</div>
                </div>
              </div>
              <div class="favorite-item-actions">
                <i class="el-icon-shopping-cart-2" title="加入购物车"></i>
                <i class="el-icon-delete" title="取消收藏"></i>
              </div>
            </div>
          </template>
        </div>
      </div>

      <!-- 账单模块 -->
      <div class="feature-card">
        <div class="card-header">
          <h3><i class="el-icon-document"></i> 我的账单</h3>
          <router-link to="/orders" class="view-all">
            <el-button type="text">查看全部 <i class="el-icon-arrow-right"></i></el-button>
          </router-link>
        </div>
        <div class="card-content">
          <template v-if="orders.length">
            <div v-for="order in orders.slice(0, 3)" :key="order.id" class="order-item">
              <div class="order-info">
                <span class="order-no">订单号：{{ order.orderNo }}</span>
                <span class="order-status" :class="'status-' + order.status">
                  {{ getOrderStatusText(order.status) }}
                </span>
              </div>
              <div class="order-amount">
                <span class="amount-label">实付金额：</span>
                <span class="amount-value">¥{{ order.payAmount }}</span>
              </div>
              <div class="order-time">{{ formatDate(order.createdTime) }}</div>
            </div>
          </template>
          <div v-else class="empty-tip">暂无订单记录~</div>
        </div>
      </div>
    </div>

    <!-- 最新动态 -->
    <div class="recent-posts">
      <div class="section-header">
        <h3><i class="el-icon-time"></i> 最新动态</h3>
      </div>
      <div class="posts-list">
        <div v-for="(form, index) in forms" :key="form.id || index" class="post-card" @click="clickpost(form.post_id)">
          <div class="post-avatar">
            <img :src="form.user_avatar" alt="用户头像"/>
          </div>
          <div class="post-content">
            <h4 class="post-title">{{ form.title }}</h4>
            <p class="post-text">{{ form.mainboby }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 个人信息抽屉 -->
    <el-drawer
      :visible.sync="drawer"
      :with-header="false"
      size="30%"
      class="profile-drawer"
    >
      <div class="drawer-content">
        <div class="drawer-header">
          <h3>编辑个人资料</h3>
          <el-button icon="el-icon-close" circle plain @click="drawer = false"></el-button>
        </div>
        <el-form label-width="80px">
          <el-form-item class="avatar-item">
            <img :src="userData.avatarUrl" class="edit-avatar-preview" alt="User Avatar">
            <el-button type="text" class="change-avatar-btn">
              <i class="el-icon-camera"></i> 更换头像
            </el-button>
          </el-form-item>
          <el-form-item label="ID">
            <el-input v-model="userData.userId" disabled></el-input>
          </el-form-item>
          <el-form-item label="用户名">
            <el-input v-model="userData.username"></el-input>
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="userData.emali"></el-input>
          </el-form-item>
          <el-form-item label="性别">
            <el-radio-group v-model="userData.sex">
              <el-radio :label="true">男</el-radio>
              <el-radio :label="false">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="出生日期">
            <el-date-picker
              v-model="userData.age"
              type="date"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="个人简介">
            <el-input type="textarea" v-model="userData.bio" rows="4"></el-input>
          </el-form-item>
        </el-form>
        <div class="drawer-footer">
          <el-button @click="drawer = false">取 消</el-button>
          <el-button type="primary" @click="save">保 存</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
export default {
  data() {
    return {
      user: {},
      posts: [],
      isAuthenticated: false,
      drawer: false,
      userData: {},
      shoppingCartItems: [],
      favoriteItems: [],
      collectedPosts: [],
      allBills: [],
      forms: [],
      orders: [],
      loading: true
    };
  },
  created() {
    this.loadUserData();
    this.loadPosts();
    this.loadShoppingCart();
    this.loadOrders();
    this.loadFavorites();
  },
  methods: {
    loadUserData() {
      this.loading = true;
      this.request.get("/users/info").then(res => {
        console.log('用户信息:', res);
        if (res.code === 1) {
          this.user = res.data;
          this.userData = { ...res.data };
          this.isAuthenticated = true;
        }
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    loadPosts() {
      this.request.get("/originalposts/list").then(res => {
        console.log('帖子列表:', res);
        if (res.code === 1) {
          this.forms = res.data.slice(0, 3); // 只显示最新3条帖子
        }
      }).catch(err => {
        console.error('获取帖子失败', err);
        this.$message.error('获取帖子列表失败');
      });
    },
    loadShoppingCart() {
      this.request.get("/cartitems/getCartList").then(res => {
        console.log('购物车:', res);
        if (res.code === 1 && res.data) {
          this.shoppingCartItems = res.data.slice(0, 3).map(item => ({
            id: item.itemId,
            name: item.name,
            price: item.price,
            quantity: item.quantity
          }));
        }
      }).catch(err => {
        console.error('获取购物车失败', err);
        this.$message.error('获取购物车失败');
      });
    },
    loadOrders() {
      this.request.get("/orders/list").then(res => {
        console.log('订单列表:', res);
        if (res.code === 1) {
          this.orders = res.data.slice(0, 3).map(order => ({
            id: order.orderId,
            orderNo: order.orderNo,
            status: order.status,
            payAmount: order.totalAmount,
            createdTime: order.createTime
          }));
        }
      }).catch(err => {
        console.error('获取订单失败', err);
        this.$message.error('获取订单列表失败');
      });
    },
    loadFavorites() {
      this.request.get("/favorites/list").then(res => {
        console.log('收藏列表:', res);
        if (res.code === 1) {
          this.favoriteItems = res.data.slice(0, 3).map(item => ({
            id: item.itemId,
            name: item.name,
            price: item.price,
            image: item.image
          }));
        }
      }).catch(err => {
        console.error('获取收藏失败', err);
        this.$message.error('获取收藏列表失败');
      });
    },
    clickpost(postId) {
      this.$router.push(`/detail/${postId}`);
    },
    createNewPost() {
      this.$router.push('/create-post'); // 确保路由存在
    },
    editProfile() {
      this.drawer = true;
    },
    openDrawer() {
      this.drawer = true;
    },
    save() {
      // 实现保存逻辑
      this.request.post("/users/update", this.userData).then(res => {
        if (res.code === 1) {
          this.$message.success("保存成功");
          this.drawer = false;
          this.loadUserData(); // 重新加载用户信息
        } else {
          this.$message.error(res.msg || "保存失败");
        }
      }).catch(err => {
        console.error('Failed to save user info', err);
        this.$message.error('保存失败');
      });
    },
    formatDate(date) {
      if (!date) return '';
      return new Date(date).toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      });
    },
    formatAge(birthDate) {
      if (!birthDate) return '';
      const age = new Date().getFullYear() - new Date(birthDate).getFullYear();
      return `${age}岁`;
    },
    toshoppingcart() {
      this.$router.push(`/mycart/${this.user.userId}`);
    },
    getOrderStatusText(status) {
      const statusMap = {
        0: '待付款',
        1: '待发货',
        2: '待收货',
        3: '已完成',
        4: '已取消'
      };
      return statusMap[status] || '未知状态';
    }
  }
};
</script>

<style scoped>
.profile-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
  box-shadow: 2px 2px 5px 0px rgba(0, 0, 0, 0.75);
  background-color: white;
  border-radius: 10px;
}

/* 个人信息头部 */
.profile-header {
  background: #fff;
  border-radius: 8px;
  padding: 24px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.user-info {
  display: flex;
  align-items: flex-start;
  cursor: pointer;
}

.avatar-wrapper {
  position: relative;
  margin-right: 24px;
  flex-shrink: 0;
}

.edit-avatar {
  position: absolute;
  bottom: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.5);
  color: #fff;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.user-details {
  flex: 1;
}

.user-main-info {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.username {
  font-size: 24px;
  color: #333;
  margin: 0;
  margin-right: 12px;
}

.user-age, .user-gender {
  font-size: 14px;
  color: #666;
  margin-right: 12px;
  background: #f5f5f5;
  padding: 2px 8px;
  border-radius: 4px;
}

.user-email {
  color: #666;
  font-size: 14px;
  margin: 8px 0;
}

.user-signature {
  color: #666;
  margin: 8px 0;
  font-size: 14px;
}

.edit-btn {
  color: #666;
  padding: 0;
}

/* 用户数据概览 */
.user-stats {
  display: flex;
  background: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
  padding: 20px 0;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.stat-item {
  flex: 1;
  text-align: center;
  position: relative;
}

.stat-item:not(:last-child)::after {
  content: '';
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  height: 60%;
  width: 1px;
  background-color: #eee;
}

.stat-value {
  font-size: 24px;
  color: #333;
  font-weight: bold;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

/* 功能区域 */
.features-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.feature-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s ease;
}

.feature-card:hover {
  transform: translateY(-2px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
  display: flex;
  align-items: center;
}

.card-header h3 i {
  margin-right: 8px;
  color: #e4393c;
}

.card-content {
  min-height: 120px;
}

.empty-tip {
  color: #999;
  text-align: center;
  padding: 20px 0;
}

/* 购物车项目 */
.cart-item, .favorite-item, .post-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #f5f5f5;
  cursor: pointer;
}

.cart-item:hover, .favorite-item:hover, .post-item:hover {
  background-color: #f9f9f9;
}

.item-name, .post-title {
  color: #333;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item-price {
  color: #e4393c;
  margin-left: 12px;
  font-weight: bold;
}

.post-date {
  color: #999;
  font-size: 12px;
  margin-left: 12px;
}

/* 账单按钮 */
.bill-buttons {
  display: flex;
  gap: 12px;
  margin-top: 12px;
}

/* 最新动态 */
.recent-posts {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.section-header {
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.section-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
  display: flex;
  align-items: center;
}

.section-header h3 i {
  margin-right: 8px;
  color: #e4393c;
}

.post-card {
  display: flex;
  padding: 16px 0;
  border-bottom: 1px solid #f5f5f5;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.post-card:hover {
  background-color: #f9f9f9;
}

.post-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 16px;
  flex-shrink: 0;
}

.post-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.post-content {
  flex: 1;
  overflow: hidden;
}

.post-title {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #333;
}

.post-text {
  margin: 0;
  color: #666;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

/* 抽屉样式 */
.profile-drawer {
  .drawer-content {
    padding: 24px;
  }

  .drawer-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
  }

  .drawer-header h3 {
    margin: 0;
    font-size: 18px;
    color: #333;
  }

  .edit-avatar-preview {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    display: block;
    margin: 0 auto 12px;
  }

  .change-avatar-btn {
    display: block;
    margin: 0 auto;
  }

  .drawer-footer {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 16px 24px;
    background: #fff;
    text-align: right;
    border-top: 1px solid #f0f0f0;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .features-grid {
    grid-template-columns: 1fr;
  }

  .user-info {
    flex-direction: column;
    text-align: center;
  }

  .avatar-wrapper {
    margin: 0 0 16px 0;
  }

  .user-main-info {
    justify-content: center;
  }
}

.order-item {
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.order-item:hover {
  background-color: #f9f9f9;
}

.order-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.order-no {
  color: #333;
  font-size: 14px;
}

.order-status {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 10px;
}

.status-0 { 
  color: #E6A23C;
  background-color: #fdf6ec;
}
.status-1 { 
  color: #409EFF;
  background-color: #ecf5ff;
}
.status-2 { 
  color: #67C23A;
  background-color: #f0f9eb;
}
.status-3 { 
  color: #909399;
  background-color: #f4f4f5;
}
.status-4 { 
  color: #F56C6C;
  background-color: #fef0f0;
}

.order-amount {
  margin-bottom: 4px;
}

.amount-label {
  color: #666;
  font-size: 12px;
}

.amount-value {
  color: #F56C6C;
  font-weight: bold;
  font-size: 14px;
}

.order-time {
  color: #999;
  font-size: 12px;
}

/* 商品收藏样式 */
.favorite-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f5f5f5;
  cursor: pointer;
}

.favorite-item:hover {
  background-color: #f9f9f9;
}

.favorite-item-content {
  display: flex;
  align-items: center;
  flex: 1;
}

.favorite-item-image {
  width: 50px;
  height: 50px;
  margin-right: 12px;
  border-radius: 4px;
  overflow: hidden;
  flex-shrink: 0;
}

.favorite-item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.favorite-item-info {
  flex: 1;
  overflow: hidden;
}

.favorite-item-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.favorite-item-price {
  font-size: 14px;
  color: #ff6600;
  font-weight: 500;
}

.favorite-item-actions {
  display: flex;
  gap: 12px;
}

.favorite-item-actions i {
  font-size: 18px;
  color: #909399;
  transition: all 0.3s;
}

.favorite-item-actions i:hover {
  color: #409EFF;
}

.favorite-item-actions i.el-icon-delete:hover {
  color: #F56C6C;
}
</style>